let mongoose = require("mongoose");
// 链接数据库-确保数据库启动起来
mongoose
  .connect("mongodb://127.0.0.1:27017/newdb")
  .then(() => {
    console.log("链接成功");
  }) 
  .catch((err) => {
    console.log(err);
  });

//   创建表结构
let UserSchema = new mongoose.Schema(
  {
    //   username: String,
    username: {
      type: String,
    },
    password: String,
  },
  {
    timestamps: true,
  }
);

// 操作表的构造函数--模型--从表结构来

let User = mongoose.model("User", UserSchema);

// 利用构造函数进行 数据的增删改查

function createUser() {
  let u1 = new User({
    username: "zhangsan",
    password: "123",
  });
  u1.save()
    .then((r) => {
      console.log("插入成功");
    })
    .catch((err) => {
      console.log("插入失败");
    });
}

function delUserWith(id) {
  return User.deleteOne({ _id: id });
}
// delUserWith("62be6d8dd9c6da5fe77acca5").then((r) => {
//   console.log("删除成功");
// });

function updateUserWith(id, obj) {
  return User.updateOne({ _id: id }, obj);
}

updateUserWith("62be6da4ee1033d4f056c257", {
  username: "zhangsanfeng",
  password: "!@#",
}).then((r) => {
  console.log(r);
});
